module Kuztuscms
  class TemplatesController < KuztuscmsController
    before_filter :build_locales_list, :only => [:new, :edit, :create, :update]
    before_filter :build_handlers_list, :only => [:new, :edit, :create, :update]
    before_filter :build_formats_list, :only => [:new, :edit, :create, :update]

    # GET /templates
    def index
      @templates = Template.all
    end

    # GET /templates/1
    def show
      @template = Template.find(params[:id])
    end

    # GET /templates/new
    def new
      @template = Template.new(:format => 'html')
    end

    # GET /templates/1/edit
    def edit
      @template = Template.find(params[:id])
    end

    # POST /templates
    def create
      @template = Template.new(params[:template])
      @template.partial = true

      if @template.save
        redirect_to templates_url, notice: 'Template was successfully created.'
      else
        render action: "new"
      end
    end

    # PUT /templates/1
    def update
      @template = Template.find(params[:id])

      if @template.update_attributes(params[:template])
        redirect_to templates_url, notice: 'Template was successfully updated.'
      else
        render action: "edit"
      end
    end

    # DELETE /templates/1
    def destroy
      @template = Template.find(params[:id])
      @template.destroy
  
      redirect_to templates_url
    end

    private 

      def build_formats_list
        @formats = Mime::SET.symbols.map(&:to_s)
      end

      def build_locales_list
        @locales = I18n.available_locales.map(&:to_s)
      end

      def build_handlers_list
        @handlers = ActionView::Template::Handlers.extensions.map(&:to_s)
      end
  end
end
